package com.example.demo.web.rest.controller;

import com.ffcs.oss.annotation.PermissionAuth;
import com.example.demo.client.evt.cssmqry.menu.UpdatePermissionByParamEvt;
import com.example.demo.client.evt.cssmqry.role.QryRoleEvt;
import com.example.demo.client.evt.cssmqry.user.QryUserEvt;
import com.example.demo.client.evt.sysbasequery.*;
import com.example.demo.client.vm.cssmqry.user.DetailUserVm;
import com.example.demo.client.vm.cssmqry.user.UserVm;
import com.example.demo.client.vm.sysbasequery.*;
import com.ffcs.oss.common.utils.LocalMessageUtil;
import com.example.demo.domain.ResourceEntity;
import com.example.demo.enums.ExportListEnum;
import com.example.demo.enums.ImportEnum;
import com.example.demo.enums.PermissionTypeEnum;
import com.example.demo.enums.UserType;
import com.example.demo.format.TreeBuilder;
import com.example.demo.mapper.RoleMapper;
import com.example.demo.mapper.UserMapper;
import com.ffcs.oss.param.out.ServiceResp;
import com.ffcs.oss.param.vm.QueryPageVm;
import com.example.demo.security.SecurityUtils;
import com.example.demo.service.ExcelService;
import com.example.demo.service.RoleService;
import com.example.demo.web.rest.constant.ExportConstant;
import com.example.demo.web.rest.evt.*;
import com.example.demo.web.rest.vm.SaveRoleWithUserVm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 角色管理
 *
 * @Author zmf
 * @Date 2018/12/14  10:19
 */
@Api("角色管理")
@RestController
@RequestMapping("/api/role")
public class RoleController extends BaseController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private ExcelService excelService;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "是否可以删除角色")
    @PostMapping("/isCanDelRole")
    public ServiceResp<Boolean> isCanDelRole(@RequestBody @Validated isCanDelRoleEvt evt) {
        evt.setLoginName(SecurityUtils.getCurrentUserLogin().get());
        return baseQueryClient.isCanDelRole(evt);
    }

    @ApiOperation(value = "删除角色")
    @PermissionAuth(code = "OSS-SETTING-ROLE-DEL")
    @PostMapping("/delRole")
    public ServiceResp<Boolean> delRole(@RequestBody @Validated IdEvt evt) {
        //判断角色是否绑定用户
        Boolean blUser = roleService.queryRoleUser(evt.getId());
        //判断角色是否绑定用户组
        Boolean blGroup = roleService.queryRoleGroup(evt.getId());
        if (blUser && blGroup) {
            roleService.delRole(evt.getId());
            return ServiceResp.getInstance(Boolean.class).success(true, "删除成功");
        } else {
            return ServiceResp.getInstance(Boolean.class).error("删除失败,该角色有绑定的用户或用户组");
        }

    }

    @ApiOperation(value = "删除角色关联用户")
    @PermissionAuth(code = "OSS-SETTING-ROLE-EDIT")
    @PostMapping("/delRoleRelateUser")
    public ServiceResp<Boolean> delRoleRelateUser(@RequestBody @Validated UserRoleEvt evt) {
        /*if(evt.getRelatedType()!=null&&"2".equals(evt.getRelatedType()+"")){
            return ServiceResp.getInstance(Boolean.class).success(false,"通过用户组关联的用户无法直接移除，请到用户组管理页面进行修改！");
        }*/
        roleService.delUserRole(evt);
        return ServiceResp.getInstance(Boolean.class).success(true, "删除成功");
    }

    @ApiOperation(value = "保存角色")
    @PermissionAuth(code = "OSS-SETTING-ROLE-EDIT,OSS-SETTING-ROLE-ADD")
    @PostMapping("/saveRole")
    public ServiceResp saveRole(@RequestBody @Validated SaveRoleEvt evt) {
        String loginName = SecurityUtils.getCurrentUserLogin().get();
        UserVm userVm = userMapper.getUser(loginName);
        Long regionId = userVm.getRegionId();
        isRoleNameExistEvt existEvt = new isRoleNameExistEvt();
        existEvt.setRegionId(regionId);
        if (evt.getRoleEvt().getRoleId() != null) {
            existEvt.setRoleId(evt.getRoleEvt().getRoleId());
        }
        existEvt.setRoleName(evt.getRoleEvt().getRoleName());
        if (baseQueryClient.isRoleNameExist(existEvt).getBody()) {
            if ("2".equals(evt.getRoleEvt().getRoleFlag() + "")) {
                return ServiceResp.getInstance().error("目录名称已存在");
            } else {
                return ServiceResp.getInstance().error("角色名称已存在");
            }

        }
        //新增校验判断 【角色ID不能与目录树ID一致】
        if (evt.getRoleEvt().getRoleId() != null && evt.getRoleEvt().getParentRoleId() != null) {
            if (evt.getRoleEvt().getRoleId().equals(evt.getRoleEvt().getParentRoleId())) {
                return ServiceResp.getInstance().error("所属目录不能选择当前编辑的目录本身！！！请重新选择目录树！！！");
            }
        }

        //控制只能编辑自己创建的角色
//        if(evt.getRoleEvt().getRoleId()!=null){
//            String user = roleMapper.qryCreateUserByRoleId(evt.getRoleEvt().getRoleId());
//            if(StringUtils.isNotBlank(user)&&!"admin".equals(SecurityUtils.getCurrentUserLogin().get())
//                    &&!user.equals(SecurityUtils.getCurrentUserLogin().get())){
//               return  ServiceResp.getInstance().error("只能对自己创建的角色进行修改！！！");
//            }
//        }
        try {
            Long roleId = roleService.saveRole(evt);
            UpdatePermissionByParamEvt updatePermissionByParamEvt = new UpdatePermissionByParamEvt();
            updatePermissionByParamEvt.setId(String.valueOf(roleId));
            updatePermissionByParamEvt.setType(PermissionTypeEnum.ROLE.getValue());
            baseQueryClient.updatePermissionByParam(updatePermissionByParamEvt);
            baseQueryClient.clearQryCache();
            return ServiceResp.getInstance(Long.class).success(roleId);
        } catch (Exception e) {
            e.printStackTrace();
            return ServiceResp.getInstance().error(e.getMessage());
        }
    }

    @ApiOperation(value = "保存角色关联用户")
    @PermissionAuth(code = "OSS-SETTING-ROLE-EDIT,OSS-SETTING-ROLE-ADD")
    @PostMapping("/saveRoleRelateUser")
    public ServiceResp<Boolean> saveRoleRelateUser(@RequestBody @Validated RelationEvt evt) {
        roleService.addUserRole(evt);
        return ServiceResp.getInstance(Boolean.class).success(true, "保存成功");
    }

    @ApiOperation(value = "保存角色关联用户(先删除原绑定数据，重新绑定新的用户信息)")
    @PermissionAuth(code = "OSS-SETTING-ROLE-EDIT,OSS-SETTING-ROLE-ADD")
    @PostMapping("/saveRoleRelateUserNew")
    public ServiceResp<Boolean> saveRoleRelateUserNew(@RequestBody @Validated RelationEvt evt) {
        roleService.addUserRoleNew(evt);
        return ServiceResp.getInstance(Boolean.class).success(true, "保存成功");
    }


    @ApiOperation("获取角色管理下拉框数据")
    @PostMapping("/getRoleStaticData")
    public ServiceResp<RoleStaticDataVm> getRoleStaticData() {
        return baseQueryClient.getRoleStaticData();
    }

    @ApiOperation("根据ID获取角色基本信息")
    @PostMapping("/getRoleById")
    public ServiceResp<RoleVm> getRoleById(@RequestBody @Validated IdEvt evt) {
        return baseQueryClient.getRoleById(evt);
    }

    @ApiOperation("角色管理获取目录树")
    @PostMapping("/getDirectoryTree")
    public ServiceResp getDirectoryTree() {
        return baseQueryClient.getDirectoryTree();
    }

    @ApiOperation("获取角色目录树")
    @PostMapping("/getRoleTree")
    public ServiceResp<List<RoleTreeVm>> getRoleTree(@RequestBody LoginNameEvt evt) {
        evt.setLoginName(SecurityUtils.getCurrentUserLogin().get());
        return baseQueryClient.getRoleTree(evt);
    }

    @ApiOperation("非管理员时当前用户是否自己创建,只能编辑自己创建的角色或目录")
    @PostMapping("/isEditRole")
    public ServiceResp<Boolean> isEditRole(@RequestBody @Validated IdEvt evt) {
        evt.setLoginName(SecurityUtils.getCurrentUserLogin().get());
        return baseQueryClient.isEditRole(evt);
    }

  /*  @ApiOperation("角色名称是否存在")
    @PostMapping("/isRoleNameExist")
    public ServiceResp<Boolean> isRoleNameExist(@RequestBody  @Validated isRoleNameExistEvt evt){
        return baseQueryClient.isRoleNameExist(evt);
    }*/

    @ApiOperation("角色关联用户查询")
    @PostMapping("/getRoleRelateUser")
    public ServiceResp<QueryPageVm<GetRoleRelateUserVm>> getRoleRelateUser(@RequestBody @Validated GetRoleRelateUserEvt evt) {
        return baseQueryClient.getRoleRelateUser(evt);
    }

    @ApiOperation("角色管理功能权限树")
    @PostMapping("/getPermissionTree")
    public ServiceResp<List<PermissionTreeVm>> getRoleRelateUser(@RequestBody @Validated IdEvt evt) {
        evt.setLoginName(SecurityUtils.getCurrentUserLogin().get());
        return baseQueryClient.getPermissionTree(evt);
    }

    @ApiOperation("获取角色目录")
    @PostMapping("/getRoleTreeMenu")
    public ServiceResp<List<RoleTreeVm>> getRoleTreeMenu(@RequestBody LoginNameEvt evt) {
        evt.setLoginName(SecurityUtils.getCurrentUserLogin().get());
        return baseQueryClient.getRoleTreeMenu(evt);
    }

    @ApiOperation("角色管理-首页")
    @PostMapping("/getRoleTreeInfos")
    public ServiceResp getRoleTreeInfos(@RequestBody QryRoleEvt evt) {
        List<RoleTreeVm> list = roleService.getRoleTreeInfos(evt);
        LoginNameEvt name = new LoginNameEvt();
        name.setLoginName(SecurityUtils.getCurrentUserLogin().get());
        name.setKeyword(evt.getKeyword());
        name.setRoleName(evt.getRoleName());
        return baseQueryClient.getRoleTree(name);
//        return ServiceResp.getInstance(List.class).success(TreeBuilder.newTreeBuilder(RoleTreeVm.class, Long.class)
//                .buildToTreeList(list));
    }

    @ApiOperation("上级角色下拉框值")
    @PostMapping(value = "/getParentRoleTree")
    public ServiceResp getParentRoleTree(@RequestBody IdEvt evt) {
        try {
            QryUserEvt qryUserEvt = new QryUserEvt();
            qryUserEvt.setLoginName(SecurityUtils.getCurrentUserLogin().get());
            DetailUserVm vm = baseQueryClient.qryDetailUser(qryUserEvt).getBody();
            evt.setRegion(vm.getRegionVm().getRegionId());
            if (vm.getUserType().equals(String.valueOf(UserType.ADMIN.getType()))) {
                evt.setRegion(null);
            }
            return ServiceResp.getInstance(List.class).success(TreeBuilder.newTreeBuilder(RoleTreeVm.class, Long.class)
                    .buildToTreeList(roleService.getParentRoleTree(evt)));
        } catch (Exception e) {
            return ServiceResp.getInstance().error(e.getMessage());
        }
    }

    @ApiOperation("角色管理资源权限树")
    @PostMapping("/getResourceTree")
    public ServiceResp<List<ResourceEntity>> getResourceTreeOfRole(@RequestBody ResourceTreeOfRoleEvt evt) {
        evt.setLoginName(SecurityUtils.getCurrentUserLogin().get());
        return baseQueryClient.getResourceTreeOfRole(evt);
    }

    @ApiOperation("导出角色列表")
    @PermissionAuth(code = "OSS-SETTING-ROLE-EXPORT")
    @GetMapping("/exportRole")
    public void exportRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            String exportFileName = LocalMessageUtil.getMessage(ExportConstant.EXPORT_ROLE_MANAGE) + ExportConstant.EXPORT_FILE_FORMAT;
            excelService.exportRoleExcel(request, response, exportFileName, ExportListEnum.ROLE.getValue());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    @ApiOperation(value = "下载角色导入模板")
    @PermissionAuth(code = "OSS-SETTING-ROLE-IMPORT")
    @GetMapping("/downloadRoleModel")
    public void downloadRoleModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String exportFileName = LocalMessageUtil.getMessage(ExportConstant.EXPORT_ROLE_MANAGE + ExportConstant.EXPORT_TEMPLATE)
                + ExportConstant.EXPORT_FILE_FORMAT;
        excelService.downloadModel(request, response, exportFileName);
    }

    @ApiOperation("导入角色")
    @PermissionAuth(code = "OSS-SETTING-ROLE-IMPORT")
    @PostMapping("/importRoleData")
    public ServiceResp importRoleData(MultipartFile file) {
        return excelService.importData(file, ImportEnum.ROLE, ImportEnum.ROLE_NOT_NULL);
    }

    @ApiOperation(value = "批量保存角色关联用户（删除和保存）")
    @PostMapping("/saveRoleWithUser")
    public ServiceResp<Boolean> saveRoleWithUser(@RequestBody SaveRoleWithUserVm vm) {
        roleService.saveRoleWithUser(vm);
        return ServiceResp.getInstance(Boolean.class).success(true, "保存成功");
    }

}
